<template>
	<view class="box box-card">
		<uni-forms ref="userForm" :modelValue="userForm" :rules="formRules" errShowType="toast">
			<uni-forms-item name="phone">
				<uni-easyinput type="number" v-model="userForm.phone" placeholder="手机号" :clearable="false"
					maxlength="11">
					<template v-slot:right>
						<button class="get-code" @click="getCode" :disabled="showTime">获取验证码
							<span v-if="showTime">({{seconds}})</span>
						</button>
					</template>
				</uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="code">
				<uni-easyinput type="password" v-model="userForm.code" placeholder="验证码" maxlength="4">
				</uni-easyinput>
			</uni-forms-item>
			<uni-forms-item>
				<button class="form-button uni-mt-10" @click="update">保存</button>
			</uni-forms-item>
		</uni-forms>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userForm: {
					phone: '',
					code: ''
				},
				showTime: false,
				seconds: 60,
				timer: null,
				formRules: {
					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入手机号码'
						}, {
							pattern: '^[1][3,4,5,7,8,9][0-9]{9}$',
							errorMessage: '请输入正确的手机号码'
						}]
					},
					code: {
						rules: [{
							required: true,
							errorMessage: '请输入验证码'
						}]
					}
				}
			}
		},
		destroyed() {
			clearInterval(this.timer);
		},
		methods: {
			getCode() {
				this.$refs.userForm.validateField(['phone']).then(() => {

					clearInterval(this.timer)
					this.showTime = true;
					this.seconds = 60;

					this.timer = setInterval(() => {
						this.seconds--;
						if (this.seconds <= 0) {
							this.showTime = false;
							clearInterval(this.timer);
						}
					}, 1000)

					this.$api.post('/appLogin/getSmsCode', {
						phone: this.userForm.phone
					}).then(res => {
						this.$util.messageTip('短信发送成功');
					})
				})
			},
			update() {
				this.$refs.userForm.validate().then(() => {
					this.$api.post('/appUser/updatePhone', this.userForm).then(res => {
						uni.reLaunch({
							url: '/pages/my/my',
							success: () => {
								this.$util.messageTip(res.message);
							}
						})
					})
				})
			}
		}
	}
</script>
